<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta
            name="viewport"
            content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
    >
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>多向拖拽</title>
    <style>
        
        .drag-container {
            width: 100px;
            height: 100px;
            border: 1px solid black;
            margin: 10px;
        }
        .drag-item {
            width: 20px;
            height: 20px;
            background: antiquewhite;
            text-align: center;
            line-height: 20px;
        }
        .dragging {
            position: absolute;
            /*opacity: 0;*/
        }
    </style>
</head>
<body>
<main>
    <section class="drag-container">
        <div id="d1" class="drag-item" draggable="true">A</div>
    </section>
    <section class="drag-container">
        <div id="d2" class="drag-item" draggable="true">B</div>
    </section>
    <section class="drag-container">
        <div id="d3" class="drag-item" draggable="true">C</div>
    </section>
</main>
<script>
    /**
     * @typedef {(from: string, to: string, item: string) => void} DropFn
     */
    /**
     * 
     * @param {HTMLElement} element
     */
    function listenDrop(element) {
        element.addEventListener("dragover", function(ev) {
            ev.preventDefault();
        });
        element.addEventListener("drop", function(ev) {
            const targetId = ev.dataTransfer.getData("itemId");
            console.log(ev.dataTransfer.getData("item"));
            ev.currentTarget.insertBefore(document.querySelector(`#${targetId}`), null);
        })
    }

    /**
     * 
     * @param {HTMLElement} element
     */
    function listenDrag(element) {
        element.addEventListener("dragstart", function(ev) {
            ev.dataTransfer.setData("itemId", ev.target.id);
            ev.target.classList.add("dragging");
        });
        element.addEventListener("drag", function(ev) {
            console.log(ev);
        });
        element.addEventListener("dragend", function(ev) {
            ev.target.classList.remove("dragging");
        })
    }
</script>
<script>
    const dis = document.querySelectorAll('.drag-item');
    dis.forEach(listenDrag)
    const dropContainer = document.querySelectorAll(".drag-container");
    dropContainer.forEach(listenDrop);
</script>
</body>
</html>